//
//  SJFriendOneViewController.m
//  WSL
//
//  Created by CJ on 2017/10/19.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJFriendOneViewController.h"
#import "SJWordItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJUserItem.h"
#import "SJExtraItem.h"
#import "SJFriendTreeApi.h"
#import "SJFetchApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>

#define TabBarHeight SJLayoutFrame(144)

@interface SJFriendOneViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate>

@property (strong, nonatomic) UIView *containView;
@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UIView *bottomView;
@property (strong, nonatomic) UIView *tabBarView;
@property (strong, nonatomic) UIImageView *tabBarBGImageView;

@property (strong, nonatomic) UIImageView *titleView;
@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UIButton *tabBarItem_0;
@property (strong, nonatomic) UIButton *tabBarItem_1;
@property (strong, nonatomic) UIButton *tabBarItem_2;
@property (strong, nonatomic) UIButton *tabBarItem_3;
@property (strong, nonatomic) UIButton *tabBarItem_4;
@property (strong, nonatomic) UIButton *tabBarItem_5;
@property (strong, nonatomic) UIButton *tabBarItem_6;
@property (strong, nonatomic) UIButton *tabBarItem_7;


@property (nonatomic, copy) NSString *isDisplayTitle;
@property (nonatomic, strong) NSMutableArray *items;


////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIImageView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;
@property (strong, nonatomic) UIButton *detailLinkButton;


@property (nonatomic, assign) CGFloat translationY;

@end

@implementation SJFriendOneViewController


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    //scrollView已经有拖拽手势，直接拿到scrollView的拖拽手势
    UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
    CGFloat translationY = [pan translationInView:scrollView].y;
    
    if (self.translationY == translationY) {
        return;
    }
    
    self.translationY = translationY;
    WeakSelf;
    if (translationY < -20) {
        //向上拖动，隐藏导航栏
        [UIView animateWithDuration:.5 animations:^{
            weakSelf.tabBarView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH - TabBarHeight);
            weakSelf.tabBarBGImageView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH - TabBarHeight);
            [weakSelf.tabBarView updateLayout];
            [weakSelf.tabBarBGImageView updateLayout];
        }];
        
    } else if (translationY > 0) {
        //向下拖动，显示导航栏
        [UIView animateWithDuration:.5 animations:^{
            weakSelf.tabBarView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
            weakSelf.tabBarBGImageView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
            [weakSelf.tabBarView updateLayout];
            [weakSelf.tabBarBGImageView updateLayout];
        }];
        
    } else if (translationY == 0) {
        //停止拖拽
        
    }
}

- (void)dealloc {
    SJLogFunc;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isDisplayTitle = @"0";
    [self.items addObject:self.item];
    [self setupUI];
    [self loadNewData];
    [self reloadTabBarData];
}

- (void)setupUI {
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout
    .leftSpaceToView(self.view, 0)
    .topSpaceToView(self.view, -SJScreenH)
    .widthIs(SJScreenW)
    .heightIs(SJScreenH * 2);
    
    [self.containView addSubview:self.topView];
    self.topView.sd_layout
    .topSpaceToView(self.containView, 0)
    .leftSpaceToView(self.containView, 0)
    .widthIs(SJScreenW)
    .heightIs(SJScreenH);
    
    [self.containView addSubview:self.collectionView];
    self.collectionView.sd_layout
    .topSpaceToView(self.topView, 0)
    .leftSpaceToView(self.containView, 0)
    .widthIs(SJScreenW)
    .heightIs(SJScreenH);
    
    // 设置 tabBar
    [self.containView addSubview:self.tabBarBGImageView];
    self.tabBarBGImageView.sd_layout
    .leftSpaceToView(self.containView, 0)
    .topSpaceToView(self.containView, SJScreenH)
    .widthIs(SJScreenW)
    .heightIs(TabBarHeight);
    
    [self.containView addSubview:self.tabBarView];
    self.tabBarView.sd_layout
    .leftSpaceToView(self.containView, 0)
    .topSpaceToView(self.containView, SJScreenH)
    .widthIs(SJScreenW)
    .heightIs(TabBarHeight);
    
    [self setupTabBar];
}

- (void)setupTabBar {
    
    [self.tabBarView addSubview:self.titleView];
    self.titleView.sd_layout
    .centerXEqualToView(self.tabBarView)
    .centerYEqualToView(self.tabBarView)
    .widthIs(SJLayoutFrame(110))
    .heightIs(SJLayoutFrame(110));
    
    [self.titleView addSubview:self.titleLabel];
    self.titleLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(30), SJLayoutFrame(10), SJLayoutFrame(30), SJLayoutFrame(10)));
    
    // itemSize
    CGFloat margin = SJLayoutFrame(10);
    CGFloat itemWH = SJLayoutFrame(42);
    
    [self.tabBarView addSubview:self.tabBarItem_0];
    self.tabBarItem_0.sd_layout
    .leftSpaceToView(self.tabBarView, margin)
    .topSpaceToView(self.tabBarView, margin)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_1];
    self.tabBarItem_1.sd_layout
    .leftSpaceToView(self.tabBarView, SJLayoutFrame(66))
    .topSpaceToView(self.tabBarView, margin)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_2];
    self.tabBarItem_2.sd_layout
    .rightSpaceToView(self.tabBarView, SJLayoutFrame(66))
    .topSpaceToView(self.tabBarView, margin)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_3];
    self.tabBarItem_3.sd_layout
    .rightSpaceToView(self.tabBarView, margin)
    .topSpaceToView(self.tabBarView, margin)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    
    [self.tabBarView addSubview:self.tabBarItem_4];
    self.tabBarItem_4.sd_layout
    .leftSpaceToView(self.tabBarView, SJLayoutFrame(38))
    .topSpaceToView(self.tabBarView, SJLayoutFrame(52))
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_5];
    self.tabBarItem_5.sd_layout
    .leftSpaceToView(self.tabBarView, SJLayoutFrame(92))
    .centerYEqualToView(self.tabBarView)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_6];
    self.tabBarItem_6.sd_layout
    .rightSpaceToView(self.tabBarView, SJLayoutFrame(92))
    .centerYEqualToView(self.tabBarView)
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    [self.tabBarView addSubview:self.tabBarItem_7];
    self.tabBarItem_7.sd_layout
    .rightSpaceToView(self.tabBarView, SJLayoutFrame(38))
    .topSpaceToView(self.tabBarView, SJLayoutFrame(52))
    .widthIs(itemWH)
    .heightIs(itemWH);
    
    
}
#pragma mark - getter

- (UIImageView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIImageView new];
        _detailImageView.image = [UIImage imageNamed:@"detail_bg_title"];
        _detailImageView.contentMode = UIViewContentModeScaleAspectFit;
        _detailImageView.alpha = 0;
        _detailImageView.userInteractionEnabled = YES;
        
        [_detailImageView addSubview:self.detailLinkButton];
        _detailLinkButton.sd_layout
        .rightSpaceToView(_detailImageView, SJLayoutFrame(20))
        .centerYEqualToView(_detailImageView)
        .widthIs(SJLayoutFrame(41))
        .heightIs(SJLayoutFrame(47));
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout
        .leftSpaceToView(_detailImageView, SJLayoutFrame(20))
        .rightSpaceToView(self.detailLinkButton, SJLayoutFrame(20))
        .topSpaceToView(_detailImageView, SJLayoutFrame(15))
        .bottomSpaceToView(_detailImageView, SJLayoutFrame(15));
        
    }
    return _detailImageView;
}

- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (UIButton *)detailLinkButton{
    
    if (!_detailLinkButton) {
        
        _detailLinkButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _detailLinkButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
        [_detailLinkButton setImage:[UIImage imageNamed:@"detail_btn_linkin"] forState:UIControlStateNormal];
        [_detailLinkButton setImage:[UIImage imageNamed:@"detail_btn_linkin"] forState:UIControlStateHighlighted];
        [_detailLinkButton addTarget:self action:@selector(detailLinkAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _detailLinkButton;
}

- (void)detailLinkAction {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = self.selectedItem.ID;
    
    SJFetchApi *api = [[SJFetchApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.selectedItem.st = @"1";
            SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
            self.detailLabel.text = extraItem.t;
            
            if (![extraItem.t isNotBlank]) {
                
                [UIView animateWithDuration:.25 animations:^{
                    self.detailImageView.alpha = 0;
                }];
            }
            
            [UIView animateWithDuration:.25 animations:^{
                self.detailLinkButton.alpha = 0;
            }];
        }
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (UILabel *)titleLabel {
    
    if (!_titleLabel) {
        
        _titleLabel = [UILabel new];
        _titleLabel.textColor = SJColorHexString(@"#ffffffff");
        _titleLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(13)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.numberOfLines = 0;
        
    }
    return _titleLabel;
}


- (UIImageView *)tabBarBGImageView{
    
    if (!_tabBarBGImageView) {
        
        _tabBarBGImageView = [UIImageView new];
        _tabBarBGImageView.image = [UIImage imageNamed:@"01_bg_0word"];
        _tabBarBGImageView.contentMode = UIViewContentModeScaleAspectFit;
        
    }
    return _tabBarBGImageView;
}

- (UIImageView *)titleView{
    
    if (!_titleView) {
        
        _titleView = [UIImageView new];
        _titleView.userInteractionEnabled = YES;
        _titleView.sd_cornerRadiusFromHeightRatio = @(0.5);
        _titleView.contentMode = UIViewContentModeScaleAspectFill;
        
        UISwipeGestureRecognizer *recognizerUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
        [recognizerUp setDirection:(UISwipeGestureRecognizerDirectionUp)];
        [_titleView addGestureRecognizer:recognizerUp];
        
        UISwipeGestureRecognizer *recognizerDown = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
        [recognizerDown setDirection:(UISwipeGestureRecognizerDirectionDown)];
        [_titleView addGestureRecognizer:recognizerDown];
        
    }
    return _titleView;
}


- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    
    if (YES) {
        
        CGFloat margin = SJLayoutFrame(10);
        CGFloat itemWH = SJLayoutFrame(42);
        WeakSelf;
        if (recognizer.direction == UISwipeGestureRecognizerDirectionUp) { // 上
            
            [UIView animateWithDuration:.5 animations:^{
                
                weakSelf.containView.sd_layout.topSpaceToView(weakSelf.view, -SJScreenH);
                weakSelf.tabBarItem_0.sd_layout.topSpaceToView(weakSelf.tabBarView, margin);
                weakSelf.tabBarItem_1.sd_layout.topSpaceToView(weakSelf.tabBarView, margin);
                weakSelf.tabBarItem_2.sd_layout.topSpaceToView(weakSelf.tabBarView, margin);
                weakSelf.tabBarItem_3.sd_layout.topSpaceToView(weakSelf.tabBarView, margin);
                weakSelf.tabBarItem_4.sd_layout.topSpaceToView(weakSelf.tabBarView, SJLayoutFrame(52));
                weakSelf.tabBarItem_7.sd_layout.topSpaceToView(weakSelf.tabBarView, SJLayoutFrame(52));
                
                weakSelf.tabBarBGImageView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
                weakSelf.tabBarView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
                [weakSelf.tabBarBGImageView updateLayout];
                [weakSelf.tabBarView updateLayout];
                
                [weakSelf.containView updateLayout];
                [weakSelf.tabBarItem_0 updateLayout];
                [weakSelf.tabBarItem_1 updateLayout];
                [weakSelf.tabBarItem_2 updateLayout];
                [weakSelf.tabBarItem_3 updateLayout];
                [weakSelf.tabBarItem_4 updateLayout];
                [weakSelf.tabBarItem_7 updateLayout];
                
                weakSelf.tabBarBGImageView.image = [UIImage imageNamed:@"01_bg_0word"];
            } completion:^(BOOL finished) {
            }];
        }
        
        if (recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
            
            [UIView animateWithDuration:.5 animations:^{ // 下
                
                weakSelf.containView.sd_layout.topSpaceToView(weakSelf.view, 0);
                weakSelf.tabBarItem_0.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - margin);
                weakSelf.tabBarItem_1.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - margin);
                weakSelf.tabBarItem_2.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - margin);
                weakSelf.tabBarItem_3.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - margin);
                weakSelf.tabBarItem_4.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - SJLayoutFrame(52));
                weakSelf.tabBarItem_7.sd_layout.topSpaceToView(weakSelf.tabBarView, TabBarHeight - itemWH - SJLayoutFrame(52));
                
                weakSelf.tabBarBGImageView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH - TabBarHeight);
                weakSelf.tabBarView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH - TabBarHeight);
                [weakSelf.tabBarBGImageView updateLayout];
                [weakSelf.tabBarView updateLayout];
                
                [weakSelf.containView updateLayout];
                [weakSelf.tabBarItem_0 updateLayout];
                [weakSelf.tabBarItem_1 updateLayout];
                [weakSelf.tabBarItem_2 updateLayout];
                [weakSelf.tabBarItem_3 updateLayout];
                [weakSelf.tabBarItem_4 updateLayout];
                [weakSelf.tabBarItem_7 updateLayout];
                
                weakSelf.tabBarBGImageView.image = [UIImage imageNamed:@"10_bg_1word"];
            } completion:^(BOOL finished) {
            }];
        }
    }
}

- (void)selectedItem:(UIButton *)button {
    
    if (button == self.tabBarItem_0) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } else if (button == self.tabBarItem_2) {
        
        self.tabBarItem_2.selected = !self.tabBarItem_2.selected;
        if (self.tabBarItem_2.selected) {
            self.isDisplayTitle = @"1";
        } else {
            self.isDisplayTitle = @"0";
        }
        [self.collectionView reloadData];
        
    } else if (button == self.tabBarItem_5) {  // 左
        
        NSInteger index = [self.items indexOfObject:self.item];
        if (index > 0) {
            
            if (index == 1) {
                self.tabBarItem_5.hidden = YES;
            }
            
            self.tabBarItem_6.hidden = NO;
            self.item = [self.items objectAtIndex:index - 1];
            [self loadNewData];
            [self reloadTabBarData];
        }
        
    } else if (button == self.tabBarItem_6) {  // 右
        
        NSInteger index = [self.items indexOfObject:self.item];
        if (index + 1 < self.items.count) {
            
            if (index + 2 == self.items.count) {
                self.tabBarItem_6.hidden = YES;
            }
            
            self.tabBarItem_5.hidden = NO;
            self.item = [self.items objectAtIndex:index + 1];
            [self loadNewData];
            [self reloadTabBarData];
        }
    }
}

- (UIButton *)tabBarItem_0{
    
    if (!_tabBarItem_0) {
        
        _tabBarItem_0 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_0.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_0 setImage:[UIImage imageNamed:@"01_btn_back"] forState:UIControlStateNormal];
        _tabBarItem_0.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_0 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_0;
}

- (UIButton *)tabBarItem_1{
    
    if (!_tabBarItem_1) {
        
        _tabBarItem_1 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_1.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_1 setImage:[UIImage imageNamed:@"01_btn_back"] forState:UIControlStateNormal];
        _tabBarItem_1.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_1 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_1;
}

- (UIButton *)tabBarItem_2{
    
    if (!_tabBarItem_2) {
        
        _tabBarItem_2 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_2.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_2 setImage:[UIImage imageNamed:@"01_btn_display_nor"] forState:UIControlStateNormal];
        [_tabBarItem_2 setImage:[UIImage imageNamed:@"01_btn_display_sel"] forState:UIControlStateSelected];
        _tabBarItem_2.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_2 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_2;
}

- (UIButton *)tabBarItem_3{
    
    if (!_tabBarItem_3) {
        
        _tabBarItem_3 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_3.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_3 setImage:[UIImage imageNamed:@"01_btn_share"] forState:UIControlStateNormal];
        _tabBarItem_3.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_3 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_3;
}

- (UIButton *)tabBarItem_4{
    
    if (!_tabBarItem_4) {
        
        _tabBarItem_4 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_4.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_4 setImage:[UIImage imageNamed:@"01_btn_grab_nor"] forState:UIControlStateNormal];
        [_tabBarItem_4 setImage:[UIImage imageNamed:@"01_btn_grab_sel"] forState:UIControlStateSelected];
        _tabBarItem_4.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_4 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_4;
}

- (UIButton *)tabBarItem_5 {
    
    if (!_tabBarItem_5) {
        
        _tabBarItem_5 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_5.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_5 setImage:[UIImage imageNamed:@"01_btn_lastword_left"] forState:UIControlStateNormal];
        _tabBarItem_5.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_5 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        _tabBarItem_5.hidden = YES;
        
    }
    return _tabBarItem_5;
}

- (UIButton *)tabBarItem_6 {
    
    if (!_tabBarItem_6) {
        
        _tabBarItem_6 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_6.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_6 setImage:[UIImage imageNamed:@"01_btn_nextword_right"] forState:UIControlStateNormal];
        _tabBarItem_6.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_6 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        _tabBarItem_6.hidden = YES;
        
    }
    return _tabBarItem_6;
}

- (UIButton *)tabBarItem_7 {
    
    if (!_tabBarItem_7) {
        
        _tabBarItem_7 = [UIButton buttonWithType:UIButtonTypeCustom];
        _tabBarItem_7.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_tabBarItem_7 setImage:[UIImage imageNamed:@"01_btn_explore"] forState:UIControlStateNormal];
        _tabBarItem_7.sd_cornerRadiusFromHeightRatio = @(0.5);
        [_tabBarItem_7 addTarget:self action:@selector(selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _tabBarItem_7;
}

- (UIView *)containView{
    
    if (!_containView) {
        
        _containView = [UIView new];
        
    }
    return _containView;
}

- (UIView *)topView{
    
    if (!_topView) {
        
        _topView = [UIView new];
        
    }
    return _topView;
}

- (UIView *)bottomView{
    
    if (!_bottomView) {
        
        _bottomView = [UIView new];
        
    }
    return _bottomView;
}

- (UIView *)tabBarView{
    
    if (!_tabBarView) {
        
        _tabBarView = [UIView new];
        
    }
    return _tabBarView;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (NSMutableArray *)items {
    
    if (!_items) {
        
        _items = [[NSMutableArray alloc] init];
        
    }
    return _items;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(TabBarHeight, 0, 0, 0);
        
        if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            if (@available(iOS 11.0, *)) {
                _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            } else {
                // Fallback on earlier versions
            }
        }
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    
    return _collectionView;
}


#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJMargin;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.isDisplayTitle = self.isDisplayTitle;
    cell.item = item;
    
    if (cell.hidden) {
        cell.hidden = NO;
    }
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark - 刷新 tabBar 数据

- (void)reloadTabBarData {
    
    if ([self.item.fmt isEqualToString:@"1"]) { // 文字
        
        self.titleLabel.text = self.item.content;
        [self.titleView setImageURL:nil];
        
    } else if ([self.item.fmt isEqualToString:@"2"]) {  // 图片
        
        self.titleLabel.text = @" ";
        
        NSString *urlString = [NSString stringWithFormat:@"%@%@", self.img_url, self.item.content];
        [self.titleView setImageWithURL:[NSURL URLWithString:urlString] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation];
    }
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"] || [item.fmt isEqualToString:@"3"] || [item.fmt isEqualToString:@"4"]) {
        return;
    }
    
    WeakSelf;
    [UIView animateWithDuration:.5 animations:^{
        weakSelf.tabBarView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
        weakSelf.tabBarBGImageView.sd_layout.topSpaceToView(weakSelf.containView, SJScreenH);
        [weakSelf.tabBarView updateLayout];
        [weakSelf.tabBarBGImageView updateLayout];
    }];
    
    [self.items addObject:item];
    self.item = item;
    
    self.tabBarItem_5.hidden = NO;
    self.tabBarItem_6.hidden = YES;
    
    [self loadNewData];
    [self reloadTabBarData];
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
    }
    
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", self.img_url, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"01_btn_delete"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", self.av_url, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
    
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", self.av_url, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", self.img_url, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    

    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
     // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}

- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(80))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    if ([self.selectedItem.st isEqualToString:@"1"]) {
        self.detailLinkButton.hidden = YES;
    }
    
    if (![extraItem.t isNotBlank] && [self.selectedItem.st isEqualToString:@"1"]) {
        self.detailImageView.hidden = YES;
    }
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
    
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLinkButton = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    // 1.拼接参数
    self.page = 0;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%ld", (long)self.page];
    parameters[@"pid"] = self.item.bid;
    parameters[@"fid"] = self.fItem.uid;
    parameters[@"id"] = self.item.ID;
    
    SJFriendTreeApi *api = [[SJFriendTreeApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {

        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            self.img_url = api.responseObject[@"content"][@"img_url"];
            self.av_url = api.responseObject[@"content"][@"av_url"];
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            self.img_url = api.responseObject[@"content"][@"img_url"];
            self.av_url = api.responseObject[@"content"][@"av_url"];
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
}


- (void)loadMoreData {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    parameters[@"pid"] = self.item.bid;
    parameters[@"fid"] = self.fItem.uid;
    parameters[@"id"] = self.item.ID;
    
    SJFriendTreeApi *api = [[SJFriendTreeApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            self.img_url = api.responseObject[@"content"][@"img_url"];
            self.av_url = api.responseObject[@"content"][@"av_url"];
        } else {
            
            self.page--;
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        self.page--;
        [self.collectionView.mj_footer endRefreshing];
    }];
}

@end

